package com.ansion.baseui.base.actionbar;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.DrawableRes;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ansion.baseui.R;
import com.ansion.baseui.base.click.AvoidDoubleClickListener;
import com.ansion.baseui.base.toolbar.TActionBarMenuUtil;
import com.ansion.baseui.base.toolbar.TMenuItem;
import com.ansion.log.VLog;
import com.ansion.utils.Pair;
import com.ansion.utils.UiUtils;
import com.ansion.baseui.base.view.SimpleDraweeViewFix;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.ValueSafeTransfer;

import java.util.Collections;
import java.util.List;


/**
 * created by zhaoyuntao
 * on 05/01/2023
 * description:
 */
public class TActionBar extends FrameLayout {

    private static final int GRAVITY_START = 0;
    private static final int GRAVITY_CENTER = 1;
    private TextView titleView;
    private TextView subtitleView;
    private TextView titleViewCenter;
    private TextView subtitleViewCenter;
    private AppCompatImageView arrowView;
    private ViewGroup customTitleContainer;
    private LinearLayout customMenuContainer;
    private PopupWindow popupWindow;

    private int gravityOfTitle = Gravity.START;
    private int menuColor = -1;
    private View mRootView;

    private List<TMenuItem> menuItemList;

    public TActionBar(@NonNull Context context) {
        super(context);
        initItemsView(null);
    }

    public TActionBar(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initItemsView(attrs);
    }

    public TActionBar(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initItemsView(attrs);
    }

    private void initItemsView(AttributeSet attrs) {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_base_actionbar, this);
        //Left arrow.
        arrowView = findViewById(R.id.actionbar_arrow);
        //Title in left.
        titleView = findViewById(R.id.actionbar_title_start);
        titleView.setVisibility(GONE);
        subtitleView = findViewById(R.id.actionbar_subtitle_start);
        subtitleView.setVisibility(GONE);
        //Title in center.
        titleViewCenter = findViewById(R.id.actionbar_title_center);
        titleViewCenter.setVisibility(GONE);
        subtitleViewCenter = findViewById(R.id.actionbar_subtitle_center);
        subtitleViewCenter.setVisibility(GONE);
        //Custom title container.
        customTitleContainer = findViewById(R.id.actionbar_container_custom_title);
        //Custom menus container.
        customMenuContainer = findViewById(R.id.actionbar_container_custom_menu);

        mRootView = findViewById(R.id.actionbar_root_view);

        if (attrs != null) {
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TActionBar);
            //Arrow
            initArrow(typedArray);
            //Title
            initTitle(typedArray);
            //Bottom shadow
            initShadow(typedArray);
            //Init back
            initBackground(typedArray);
            //Init root back
            initRootBackground(typedArray);
            typedArray.recycle();
        }
    }

    private void initBackground(TypedArray typedArray) {
        setBackgroundColor(typedArray.getColor(R.styleable.TActionBar_TActionBarBackgroundColor, ContextCompat.getColor(getContext(), R.color.gray_1)));
    }

    private void initRootBackground(TypedArray typedArray) {
        mRootView.setBackgroundColor(typedArray.getColor(R.styleable.TActionBar_TActionBarRootBackgroundColor, ContextCompat.getColor(getContext(), R.color.gray_1)));
    }

    private void initShadow(TypedArray typedArray) {
        boolean showBottomShadow = typedArray.getBoolean(R.styleable.TActionBar_TActionBarShowBottomShadow, false);
        if (showBottomShadow) {
            setElevation(UiUtils.dipToPx(1));
            setTranslationZ(UiUtils.dipToPx(1));
        }
    }

    private void initArrow(TypedArray typedArray) {
        boolean showArrow = typedArray.getBoolean(R.styleable.TActionBar_TActionBarShowArrow, true);
        arrowView.setVisibility(showArrow ? VISIBLE : GONE);
        if (typedArray.hasValue(R.styleable.TActionBar_TActionBarArrowTintColor)) {
            int colorTint = typedArray.getColor(R.styleable.TActionBar_TActionBarArrowTintColor, Color.WHITE);
            arrowView.setImageTintList(ColorStateList.valueOf(colorTint));
        }
        Drawable drawable = typedArray.getDrawable(R.styleable.TActionBar_TActionBarArrowDrawable);
        if (drawable != null) {
            arrowView.setImageDrawable(drawable);
        }
    }

    private void initTitle(TypedArray typedArray) {
        String title = typedArray.getString(R.styleable.TActionBar_TActionBarTitle);
        String subtitle = typedArray.getString(R.styleable.TActionBar_TActionBarSubtitle);
        if (TextUtils.isEmpty(title)) {
            title = typedArray.getString(R.styleable.TActionBar_TActionBarTitleCenter);
            if (!TextUtils.isEmpty(title)) {
                gravityOfTitle = Gravity.CENTER;
                setTitle(title, gravityOfTitle);
                return;
            }
        }
        if (TextUtils.isEmpty(subtitle)) {
            subtitle = typedArray.getString(R.styleable.TActionBar_TActionBarSubtitleCenter);
            if (!TextUtils.isEmpty(subtitle)) {
                setSubtitle(subtitle, gravityOfTitle);
            }
        }
        int gravity = typedArray.getInt(R.styleable.TActionBar_TActionBarTitleGravity, GRAVITY_START);
        if (gravity == GRAVITY_CENTER) {
            gravityOfTitle = Gravity.CENTER;
        } else {
            gravityOfTitle = Gravity.START;
        }
        setTitle(title, gravityOfTitle);
        //Text size and color.
        float textSize = typedArray.getDimension(R.styleable.TActionBar_TActionBarTitleTextSize, 0);
        if (textSize > 0) {
            setTitleTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }
        float subtitleTextSize = typedArray.getDimension(R.styleable.TActionBar_TActionBarSubtitleTextSize, 0);
        if (subtitleTextSize > 0) {
            setSubtitleTextSize(TypedValue.COMPLEX_UNIT_PX, subtitleTextSize);
        }
        int textColor = typedArray.getColor(R.styleable.TActionBar_TActionBarTitleTextColor, ContextCompat.getColor(getContext(), R.color.white));
        setTitleColor(textColor);
        int subtitleTextColor = typedArray.getColor(R.styleable.TActionBar_TActionBarSubtitleTextColor, ContextCompat.getColor(getContext(), R.color.white));
        setSubTitleColor(subtitleTextColor);
        if (typedArray.hasValue(R.styleable.TActionBar_TActionBarImageMenuTintColor)) {
            menuColor = typedArray.getColor(R.styleable.TActionBar_TActionBarImageMenuTintColor, ResourceUtils.getColor(R.color.bot_level1_base_color));
            setMenuColor(menuColor);
        }
    }

    final public void setMenuColor(int menuColor) {
        this.menuColor = menuColor;
        int childCount = customMenuContainer.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = customMenuContainer.getChildAt(i);
            if (child instanceof TextView) {
                ((TextView) child).setTextColor(menuColor);
            } else if (child instanceof ImageView) {
                ((ImageView) child).setImageTintList(ColorStateList.valueOf(menuColor));
            }
        }
    }

    final public void setTitleTextSize(int unit, float textSize) {
        if (titleView != null) {
            titleView.setTextSize(unit, textSize);
            titleViewCenter.setTextSize(unit, textSize);
        }
    }

    public void setTitleColor(@ColorInt int textColor) {
        if (titleView != null) {
            titleView.setTextColor(textColor);
            titleViewCenter.setTextColor(textColor);
        }
    }

    private void initTitleVisible() {
        if (customTitleContainer.getChildCount() > 0) {
            titleView.setVisibility(GONE);
            subtitleView.setVisibility(GONE);
            titleViewCenter.setVisibility(GONE);
            subtitleViewCenter.setVisibility(GONE);
        } else {
            if (gravityOfTitle == Gravity.CENTER) {
                titleViewCenter.setVisibility(TextUtils.isEmpty(titleViewCenter.getText()) ? GONE : VISIBLE);
                subtitleViewCenter.setVisibility(TextUtils.isEmpty(subtitleViewCenter.getText()) ? GONE : VISIBLE);
                titleView.setVisibility(GONE);
                subtitleView.setVisibility(GONE);
            } else {
                titleView.setVisibility(TextUtils.isEmpty(titleView.getText()) ? GONE : VISIBLE);
                subtitleView.setVisibility(TextUtils.isEmpty(subtitleView.getText()) ? GONE : VISIBLE);
                titleViewCenter.setVisibility(GONE);
                subtitleViewCenter.setVisibility(GONE);
            }
        }
    }

    final public void setTitle(CharSequence title) {
        setTitle(title, gravityOfTitle);
    }

    final public void setTitle(CharSequence title, int gravity) {
        this.gravityOfTitle = gravity;
        if (TextUtils.isEmpty(title)) {
            return;
        }
        if (gravityOfTitle == Gravity.CENTER) {
            titleViewCenter.setText(title);
        } else {
            titleView.setText(title);
        }
        initTitleVisible();
    }

    final public void setSubtitle(CharSequence subtitle) {
        setSubtitle(subtitle, gravityOfTitle);
    }

    final public void setSubtitle(CharSequence subtitle, int gravity) {
        this.gravityOfTitle = gravity;
        if (gravityOfTitle == Gravity.CENTER) {
            subtitleViewCenter.setText(subtitle);
        } else {
            subtitleView.setText(subtitle);
        }
        initTitleVisible();
    }

    final public void setSubtitleTextSize(int unit, float textSize) {
        if (subtitleView != null) {
            subtitleView.setTextSize(unit, textSize);
            subtitleViewCenter.setTextSize(unit, textSize);
        }
    }

    public void setSubTitleColor(@ColorInt int textColor) {
        if (subtitleView != null) {
            subtitleView.setTextColor(textColor);
            subtitleViewCenter.setTextColor(textColor);
        }
    }

    final public void setViewPadding(@IdRes int viewId, int left, int top, int right, int bot) {
        View view = findViewById(viewId);
        if (view != null) {
            view.setPadding(left, top, right, bot);
        }
    }

    final public void setTextSize(@IdRes int viewId, float textSize) {
        TextView view = findViewById(viewId);
        if (view != null) {
            view.setTextSize(textSize);
        }
    }

    final public void setText(@IdRes int viewId, @StringRes int resource) {
        TextView view = findViewById(viewId);
        if (view != null) {
            view.setText(resource);
        }
    }

    final public void setText(@IdRes int viewId, CharSequence title) {
        TextView view = findViewById(viewId);
        if (view != null) {
            view.setText(title);
        }
    }

    final public void setTextColor(@IdRes int viewId, @ColorRes int textColor) {
        TextView view = findViewById(viewId);
        if (view != null) {
            view.setTextColor(ContextCompat.getColor(getContext(), textColor));
        }
    }

    final public void setViewEnable(@IdRes int viewId, boolean enable) {
        View view = findViewById(viewId);
        if (view != null) {
            view.setEnabled(enable);
        }
    }

    final public void setArrowViewClickListener(OnClickListener listener) {
        arrowView.setOnClickListener(new AvoidDoubleClickListener() {
            @Override
            public void onClickView(View view) {
                listener.onClick(view);
            }
        });
    }

    final public void setArrowViewTintColor(@ColorInt int color) {
        arrowView.setImageTintList(ColorStateList.valueOf(color));
    }

    final public void setArrowViewTintColorRes(@ColorRes int colorRes) {
        arrowView.setImageTintList(ColorStateList.valueOf(ResourceUtils.getColor(colorRes)));
    }

    final public void setArrowImage(@DrawableRes int res) {
        arrowView.setImageDrawable(getContext().getDrawable(res));
    }

    final public void setArrowViewVisible(boolean visible) {
        arrowView.setVisibility(visible ? VISIBLE : GONE);
    }

    final public void setTitleViewClickListener(OnClickListener listener) {
        titleView.setOnClickListener(new AvoidDoubleClickListener() {
            @Override
            public void onClickView(View view) {
                listener.onClick(view);
            }
        });
        titleViewCenter.setOnClickListener(new AvoidDoubleClickListener() {
            @Override
            public void onClickView(View view) {
                listener.onClick(view);
            }
        });
    }

    public View setCustomTitleView(@LayoutRes int layoutId) {
        return setCustomTitleView(LayoutInflater.from(getContext()).inflate(layoutId, null));
    }

    public View setCustomTitleView(View view) {
        clearCustomTitle();
        customTitleContainer.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        initTitleVisible();
        return view;
    }

    public void clearCustomTitle(){
        if (customTitleContainer.getChildCount() > 0) {
            customTitleContainer.removeAllViews();
        }
    }

    public void clearMenu() {
        customMenuContainer.removeAllViews();
        if (customMenuContainer.getVisibility() != View.GONE) {
            customMenuContainer.animate().alphaBy(1.0f).alpha(0).setDuration(300).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    customMenuContainer.setVisibility(GONE);
                }
            });
        }
    }

    public void setMenus(@Nullable TMenuItem... menus) {
        setMenus(ValueSafeTransfer.asList(menus));
    }

    public void setMenus(@Nullable List<TMenuItem> menus) {
        if (menus == null || menus.isEmpty()) {
            clearMenu();
            return;
        }
        customMenuContainer.removeAllViews();
        Collections.sort(menus, (o1, o2) -> Integer.compare(o1.getOrderId(), o2.getOrderId()));

        //Save the menu list.
        menuItemList = menus;
        for (TMenuItem menuItem : menus) {
            if (!menuItem.isVisible()) {
                continue;
            }
            boolean hasText = menuItem.hasText() || menuItem.hasTextRes();
            boolean hasDrawable = menuItem.hasDrawableRes() || menuItem.hasDrawableURL() || menuItem.hasDrawable();
            if (menuItem.hasPopMenu()) {
                closePopWindow();
                popupWindow = new PopupWindow(LayoutInflater.from(getContext()).inflate(R.layout.layout_actionbar_pop_menu_list, null), WRAP_CONTENT, WRAP_CONTENT);
                popupWindow.setAnimationStyle(UiUtils.isRTL() ? R.style.actionbar_animation_rtl : R.style.actionbar_animation);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setFocusable(true);

                RecyclerView menuMoreListView = popupWindow.getContentView().findViewById(R.id.recycler_view_actionbar_pop_menu);
                menuMoreListView.setLayoutManager(new LinearLayoutManager(getContext()));
                TMenuAdapter adapter = new TMenuAdapter(new TMenuAdapter.OnItemClickListener() {
                    @Override
                    public void onItemClicked(View view, TMenuItem tMenuItem) {
                        popupWindow.dismiss();
                    }
                });
                menuMoreListView.setAdapter(adapter);
                menuItem.setListener(v -> {
                    if (popupWindow.isShowing()) {
                        popupWindow.dismiss();
                    } else {
                        adapter.submitList(menuItem.getPopMenus());
                        if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
                            //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                            popupWindow.showAsDropDown(v, -v.getWidth() - UiUtils.dipToPx(8), 0);
                        } else {
                            //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                            popupWindow.showAsDropDown(v, -popupWindow.getWidth() + v.getWidth(), 0);
                        }
                    }
                });
                View menuView = menuItem.hasDrawableURL() ? createFrescoMenu(menuItem) : createImageMenu(menuItem);
                customMenuContainer.addView(menuView);
            } else {
                View menuView;
                if (hasDrawable) {
                    menuView = menuItem.hasDrawableURL() ? createFrescoMenu(menuItem) : createImageMenu(menuItem);
                } else if (hasText) {
                    menuView = createTextMenu(menuItem);
                } else {
                    VLog.e("TActionBar", "You have to set text or image for the menu item!");
                    continue;
                }
                customMenuContainer.addView(menuView);
            }
        }
        if (customMenuContainer.getChildCount() > 0) {
            customMenuContainer.setVisibility(VISIBLE);
            customMenuContainer.animate().alphaBy(0).alpha(1.0f).setDuration(300).setListener(null);
        }
    }

    public void updateAndShowPopMenu(@Nullable List<TMenuItem> popItems, View v) {
        if (popItems == null || popItems.isEmpty()) {
            return;
        }
        closePopWindow();
        popupWindow = new PopupWindow(LayoutInflater.from(getContext()).inflate(R.layout.layout_actionbar_pop_menu_list, null), WRAP_CONTENT, WRAP_CONTENT);
        popupWindow.setAnimationStyle(UiUtils.isRTL() ? R.style.actionbar_animation_rtl : R.style.actionbar_animation);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setFocusable(true);

        RecyclerView menuMoreListView = popupWindow.getContentView().findViewById(R.id.recycler_view_actionbar_pop_menu);
        menuMoreListView.setLayoutManager(new LinearLayoutManager(getContext()));
        TMenuAdapter adapter = new TMenuAdapter(new TMenuAdapter.OnItemClickListener() {
            @Override
            public void onItemClicked(View view, TMenuItem tMenuItem) {
                popupWindow.dismiss();
            }
        });
        menuMoreListView.setAdapter(adapter);
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            adapter.submitList(popItems);
            if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
                //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                popupWindow.showAsDropDown(v, -v.getWidth() - UiUtils.dipToPx(8), 0);
            } else {
                //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                popupWindow.showAsDropDown(v, -popupWindow.getWidth() + v.getWidth(), 0);
            }
        }
    }

    @NonNull
    private AppCompatTextView createTextMenu(@NonNull TMenuItem menuItem) {
        AppCompatTextView textView = new AppCompatTextView(getContext());
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
        textView.setMinWidth(UiUtils.dipToPx(42));
        textView.setMaxWidth(UiUtils.dipToPx(100));
        textView.setGravity(Gravity.CENTER);
        TActionBarMenuUtil.setMenuParams(textView, menuItem);
        int padding = UiUtils.dipToPx(12);
        textView.setPaddingRelative(padding, 0, padding, 0);
        textView.setOnClickListener(menuItem.getListener());
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(WRAP_CONTENT, UiUtils.dipToPx(32));
        lp.gravity = Gravity.CENTER_VERTICAL;
        int marginStartEnd = UiUtils.dipToPx(4);
        lp.setMarginStart(marginStartEnd);
        lp.setMarginEnd(marginStartEnd);
        textView.setLayoutParams(lp);
        return textView;
    }

    @NonNull
    private AppCompatImageView createImageMenu(@NonNull TMenuItem menuItem) {
        AppCompatImageView imageView = new AppCompatImageView(getContext());
        int padding = menuItem.hasDrawablePadding() ? menuItem.getDrawablePadding() : UiUtils.dipToPx(4);
        imageView.setPaddingRelative(padding, padding, padding, padding);
        imageView.setOnClickListener(menuItem.getListener());
        if (menuItem.hasDrawableBackgroundRes()) {
            imageView.setBackgroundResource(menuItem.getDrawableBackgroundRes());
        }
        if (menuItem.hasDrawableLayoutParams()) {
            imageView.setLayoutParams(menuItem.getDrawableLayoutParams());
        } else {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(UiUtils.dipToPx(32), UiUtils.dipToPx(32));
            lp.gravity = Gravity.CENTER_VERTICAL;
            int marginStartEnd = UiUtils.dipToPx(4);
            lp.setMarginStart(marginStartEnd);
            lp.setMarginEnd(marginStartEnd);
            imageView.setLayoutParams(lp);
        }
        TActionBarMenuUtil.setMenuParams(imageView, menuItem);
        return imageView;
    }

    @NonNull
    private SimpleDraweeViewFix createFrescoMenu(@NonNull TMenuItem menuItem) {
        SimpleDraweeViewFix imageView = new SimpleDraweeViewFix(getContext());
        int padding = menuItem.hasDrawablePadding() ? menuItem.getDrawablePadding() : UiUtils.dipToPx(4);
        imageView.setPaddingRelative(padding, padding, padding, padding);
        imageView.setOnClickListener(menuItem.getListener());

        if (menuItem.hasDrawableBackgroundRes()) {
            imageView.setBackgroundResource(menuItem.getDrawableBackgroundRes());
        }
        if (menuItem.hasDrawableLayoutParams()) {
            imageView.setLayoutParams(menuItem.getDrawableLayoutParams());
        } else {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(UiUtils.dipToPx(32), UiUtils.dipToPx(32));
            lp.gravity = Gravity.CENTER_VERTICAL;
            int marginStartEnd = UiUtils.dipToPx(4);
            lp.setMarginStart(marginStartEnd);
            lp.setMarginEnd(marginStartEnd);
            imageView.setLayoutParams(lp);
        }
        TActionBarMenuUtil.setMenuParams(imageView, menuItem);
        return imageView;
    }

    public void closePopWindow() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    public View getMenuContainerChildViewByTag(String menuItemTag) {
        Pair<Integer, TMenuItem> tMenuItemPair = getIndexOfMenuContainerChildByTag(menuItemTag);
        int tMenuItemIndex = ValueSafeTransfer.value(tMenuItemPair.first, -1);
        if (tMenuItemIndex == -1 || tMenuItemPair.second == null) {
            return null;
        }
        return getMenuContainerChildView(tMenuItemIndex);
    }

    public Pair<Integer, TMenuItem> getIndexOfMenuContainerChildByTag(String menuItemTag) {
        if (TextUtils.isEmpty(menuItemTag) || menuItemList == null || menuItemList.isEmpty()) {
            return Pair.create(-1, null);
        }

        for (int i = 0; i < menuItemList.size(); i++) {
            if (menuItemList.get(i) != null && menuItemTag.equals(menuItemList.get(i).getMenuItemTag())) {
                return Pair.create(i, menuItemList.get(i));
            }
        }
        return Pair.create(-1, null);
    }

    public View getMenuContainerChildView(int index) {
        if (customMenuContainer == null || index < 0 || index >= customMenuContainer.getChildCount()) {
            return null;
        }
        return customMenuContainer.getChildAt(index);
    }

    public void updateMenuItemByView(TMenuItem menuItem, View childView, int index) {
        if (menuItem == null || childView == null) {
            return;
        }

        if (!menuItem.isVisible()) {
            if (menuItemList != null && index < menuItemList.size()) {
                menuItemList.remove(index);
            }
            customMenuContainer.removeView(childView);
        } else {
            if (childView instanceof TextView) {
                TextView childTvView = (TextView) childView;
                TActionBarMenuUtil.setMenuParams(childTvView, menuItem);
                childTvView.setOnClickListener(menuItem.getListener());
            } else if (childView instanceof AppCompatImageView) {
                AppCompatImageView childIvView = (AppCompatImageView) childView;
                int padding = menuItem.hasDrawablePadding() ? menuItem.getDrawablePadding() : UiUtils.dipToPx(4);
                childIvView.setPaddingRelative(padding, padding, padding, padding);
                childIvView.setOnClickListener(menuItem.getListener());
                if (menuItem.hasDrawableBackgroundRes()) {
                    childIvView.setBackgroundResource(menuItem.getDrawableBackgroundRes());
                }
                if (menuItem.hasDrawableLayoutParams()) {
                    childIvView.setLayoutParams(menuItem.getDrawableLayoutParams());
                }
                TActionBarMenuUtil.setMenuParams(childIvView, menuItem);
            } else if (childView instanceof SimpleDraweeViewFix) {
                SimpleDraweeViewFix childSimpleDraweeViewFix = (SimpleDraweeViewFix) childView;
                int padding = menuItem.hasDrawablePadding() ? menuItem.getDrawablePadding() : UiUtils.dipToPx(4);
                childSimpleDraweeViewFix.setPaddingRelative(padding, padding, padding, padding);
                childSimpleDraweeViewFix.setOnClickListener(menuItem.getListener());

                if (menuItem.hasDrawableBackgroundRes()) {
                    childSimpleDraweeViewFix.setBackgroundResource(menuItem.getDrawableBackgroundRes());
                }
                if (menuItem.hasDrawableLayoutParams()) {
                    childSimpleDraweeViewFix.setLayoutParams(menuItem.getDrawableLayoutParams());
                }
                TActionBarMenuUtil.setMenuParams(childSimpleDraweeViewFix, menuItem);
            }
            if (menuItemList != null && index < menuItemList.size()) {
                menuItemList.set(index, menuItem);
            }
        }
    }

    public void addMenuContainerItem(TMenuItem menuItem, int index) {
        if (customMenuContainer == null
                || menuItem == null
                || menuItemList == null
                || index < 0
                || index > menuItemList.size()) {
            return;
        }

        if (!menuItem.isVisible()) {
            return;
        }

        menuItemList.add(index, menuItem);
        boolean hasText = menuItem.hasText() || menuItem.hasTextRes();
        boolean hasDrawable = menuItem.hasDrawableRes() || menuItem.hasDrawableURL() || menuItem.hasDrawable();
        if (menuItem.hasPopMenu()) {
            closePopWindow();
            popupWindow = new PopupWindow(LayoutInflater.from(getContext()).inflate(R.layout.layout_actionbar_pop_menu_list, null), WRAP_CONTENT, WRAP_CONTENT);
            popupWindow.setAnimationStyle(UiUtils.isRTL() ? R.style.actionbar_animation_rtl : R.style.actionbar_animation);
            popupWindow.setOutsideTouchable(true);
            popupWindow.setFocusable(true);

            RecyclerView menuMoreListView = popupWindow.getContentView().findViewById(R.id.recycler_view_actionbar_pop_menu);
            menuMoreListView.setLayoutManager(new LinearLayoutManager(getContext()));
            TMenuAdapter adapter = new TMenuAdapter(new TMenuAdapter.OnItemClickListener() {
                @Override
                public void onItemClicked(View view, TMenuItem tMenuItem) {
                    popupWindow.dismiss();
                }
            });
            menuMoreListView.setAdapter(adapter);
            menuItem.setListener(v -> {
                if (popupWindow.isShowing()) {
                    popupWindow.dismiss();
                } else {
                    adapter.submitList(menuItem.getPopMenus());
                    if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
                        //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                        popupWindow.showAsDropDown(v, -v.getWidth() - UiUtils.dipToPx(8), 0);
                    } else {
                        //由于靠左/右显示不下popupWindow，所以采用了默认填充效果，直接贴着屏幕边缘显示，设置xOffset没啥用，随便设置
                        popupWindow.showAsDropDown(v, -popupWindow.getWidth() + v.getWidth(), 0);
                    }
                }
            });
            View menuView = menuItem.hasDrawableURL() ? createFrescoMenu(menuItem) : createImageMenu(menuItem);
            customMenuContainer.addView(menuView, index);
        } else {
            View menuView;
            if (hasDrawable) {
                menuView = menuItem.hasDrawableURL() ? createFrescoMenu(menuItem) : createImageMenu(menuItem);
            } else if (hasText) {
                menuView = createTextMenu(menuItem);
            } else {
                VLog.e("TActionBar", "You have to set text or image for the menu item!");
                return;
            }
            customMenuContainer.addView(menuView, index);
        }
    }
}
